package com.ybbase.framework.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ybbase.framework.mapper.system.OrganizationMapper;
import com.ybbase.framework.mapper.system.RoleMapper;
import com.ybbase.framework.mapper.system.UserPermissionMapper;
import com.ybbase.framework.model.po.system.Organization;
import com.ybbase.framework.model.po.system.Role;
import com.ybbase.framework.model.po.system.User;
import com.ybbase.framework.model.po.system.UserPermission;
import com.ybbase.framework.service.system.AbstractDataAuthService;
import com.ybbase.framework.service.system.OrganizationService;
import com.ybbase.framework.service.system.RoleService;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 执行方法
 *
 * @author cg
 * @date 2020-01-27 22:26
 * @since cloud2.0
 */
@Service
public class AbstractDataAuthServiceImpl implements AbstractDataAuthService {

    private static final Logger LOG = LoggerFactory.getLogger(AbstractDataAuthServiceImpl.class);
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    OrganizationMapper organizationMapper;
    @Autowired
    UserPermissionMapper userPermissionMapper;

    /**
     * 默认查询sql,根据角色不同追加不同业务查询条件
     *
     * @return
     */
    @Override
    public String whereSql(String tableAlias,String dataMethod) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        try {
            StringBuffer sql = new StringBuffer();
            if (user != null) {
                if (!StringUtils.isEmpty(tableAlias)) {
                    tableAlias = tableAlias + ".";
                }
                // 普通 用户
                if (user.getIsAdmin() == 0) {
                    sql.append(nomalUserSql(user.getId(), tableAlias,dataMethod));
                }
                // 管理员
                else {
                    sql.append(managerSql(tableAlias));
                }
            }
            return sql.toString();
        } catch (Exception e) {
            e.printStackTrace();
            LOG.error(e.getMessage());
            return "";
        }
    }

    /**
     * 普通用户执行sql
     *
     * @param
     * @return
     * @author cg
     * @date 2020-01-27 22:33
     * @since cloud2.0
     */
    public String nomalUserSql(Integer userId, String tableAlias,String dataMethod) throws Exception {
        QueryWrapper<UserPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserPermission::getUserId, userId);
        List<UserPermission> userPermissions = userPermissionMapper.selectList(queryWrapper);
        Integer dataScope = 0;
        if(userPermissions!=null && !userPermissions.isEmpty()){
            for (UserPermission up:userPermissions){
                if (up.getDataMethod().equals(dataMethod)){
                    dataScope = up.getDataScope();
                    break;
                }else{
                    if (up.getDataScope() > dataScope){
                        dataScope = up.getDataScope();
                    }
                }
            }
        }
        //List<Role> roleList = roleMapper.getRoleListByUserId(userId);
        //Integer dataScope = 0;
        //if (roleList != null && !roleList.isEmpty()) {
        //    for (Role role : roleList) {
        //        if (role.getDataScope() > dataScope) {
        //            dataScope = role.getDataScope();
        //        }
        //    }
        //}
        return assibleSql(userId, dataScope, tableAlias);
    }

    /**
     * 拼装sql
     *
     * @param
     * @return
     * @author cg
     * @date 2020-01-27 23:33
     * @since cloud2.0
     */
    public String assibleSql(Integer userId, Integer dataScope, String tableAlias) throws Exception {
        StringBuffer sql = new StringBuffer();
        String st = "";
        Organization organization = new Organization();

        List<Organization> list = organizationMapper.getOrgListByUserId(userId);
        if (list != null && !list.isEmpty()) {
            organization = list.get(0);
        }
        switch (dataScope) {
            case 0:
                sql.append(tableAlias + "create_by = " + userId);
                break;
            case 1:
                sql.append(tableAlias + "organ_id = " + organization.getId());
                break;
            case 2:
                sql.append(tableAlias + "organ_id in (" + getOrgIds(userId, organization, 2) + ")");
                break;
            case 3:
                sql.append(tableAlias + "organ_id in (" + getOrgIds(userId, organization, 1) + ")");
                break;
            default:
                break;
        }
        return sql.toString();
    }

    /**
     * 根据组织机构的path查询数据权限
     *
     * @param
     * @return
     * @author cg
     * @date 2020-01-27 23:33
     * @since cloud2.0
     */
    public String getOrgIds(Integer userId, Organization organization, Integer type) throws Exception {
        Organization lsOrgan = new Organization();
        String ids = "";
        String[] organIds = organization.getPath().split("[|]");
        if (organIds != null && organIds.length > 0) {
            List<Organization> lists = organizationMapper.getOrgListQuery(organIds, type);
            if (lists != null && !lists.isEmpty()) {
                lsOrgan = lists.get(0);
            }
        }
        if (lsOrgan != null) {
            List<Organization> listOrgs = organizationMapper.getOrgListByPath(lsOrgan.getPath());
            if (listOrgs != null && !listOrgs.isEmpty()) {
                for (Organization o : listOrgs) {
                    if ("".equals(ids)) {
                        ids = o.getId() + "";
                    } else {
                        ids = ids + "," + o.getId();
                    }
                }
            }
        }
        return ids;
    }

    /**
     * 管理员执行sql
     *
     * @param
     * @return
     * @author cg
     * @date 2020-01-27 22:33
     * @since cloud2.0
     */
    public String managerSql(String tableAlias) {
        return "";
    }
}
